<?php
/**
 * Author: yixuan
 * Desc:缓存操作函数（数据库）
 * require_path: 挂载文件路径  application/common.php:16
 * Time: 2016/5/18 17:31
 */

use think\Db;


/**
 * Desc:写缓存
 * User: yixuan
 * Time: 2016/5/18 19:04
 * @param $key
 * @param $value
 * @param $expire
 * @return int
 */
if (!function_exists('cache_write')) {
    function cache_write($key, $value, $expire = 0)
    {
        $cache = Db::table('yx_sys_cache')
            ->where('key', $key)
            ->field('key')
            ->find();
        $data = [];
        $data['key'] = $key;
        $data['value'] = json_encode($value);
        $data['timestamp'] = $expire > 0 ? time() + $expire : 0;
        if (empty($cache)) {
            $result = DB::table('yx_sys_cache')->insert($data);
        } else {
            $result = DB::table('yx_sys_cache')
                ->where('key', $cache['key'])
                ->update($data);
        }
        return $result;
    }
}
/**
 * Desc:读缓存
 * User: yixuan
 * Time: 2016/5/18 16:12
 * @param $key
 * @param $data
 * @param $expire
 */
if (!function_exists('cache_load')) {
    function cache_load($key)
    {
        $cache = Db::table('yx_sys_cache')
            ->where('key', $key)
            ->find();
        $return_data = [];
        $time = time();
        if (!empty($cache)) {
            if ($cache['timestamp'] > $time || $cache['timestamp'] == 0) {
                $return_data = json_decode($cache['value'], true);
            } elseif ($cache['timestamp'] < $time && $cache['timestamp'] != 0) {
                cache_delete($key);
            }
        }
        $h = date("H");
        if ($h >= 7 && $h < 8) {
            Db::table('yx_sys_cache')->where("timestamp < $time and timestamp!=0")->delete();
        }
        return $return_data;
    }
}
/**
 * Desc:删除指定的缓存
 * User: yixuan
 * Time: 2016/5/18 16:13
 * @param $key
 * @param $data
 * @param $expire
 */
if (!function_exists('cache_delete')) {
    function cache_delete($key)
    {
        if (empty($key)) {
            return false;
        }
        $result = Db::table('yx_sys_cache')->where('key', $key)->delete();
        return $result;
    }
}
/**
 * Desc:删除所有缓存
 * User: yixuan
 * Time: 2016/5/18 16:13
 * @param $key
 * @param $data
 * @param $expire
 */
if (!function_exists('cache_clean')) {
    function cache_clean()
    {
        $result = Db::query("TRUNCATE TABLE yx_sys_cache;");
        return $result;
    }
}